//
//  AppManager.swift
//  live
//
//  Created by melvyn on 2018/8/9.
//  Copyright © 2018年 NEET. All rights reserved.
//

import Foundation
import Link
import RxSwift
import RxCocoa

class AppManager {
    
    var user: BehaviorRelay<User?> = BehaviorRelay(value: nil)
    var API: Reactive<APIClient> {
        return APIRelay.value.rx
    }
    
    private var APIRelay: BehaviorRelay<APIClient>
    private var disposeBag = DisposeBag()
    
    static var `default`: AppManager = {
        return AppManager.init()
    }()
    
    init() {
        APIRelay = .init(value: APIClient.init(userID: Link.shared.sessionStore.session?.userID ?? -1))
        
        setup()
    }
    
    private func setup() {
        
        NotificationCenter.default.rx.notification(.userDidLoggedIn)
            .map({ $0.userInfo?[Link.loggedInUserIDKey] as? AuthSession.ID })
            .unwrap()
            .map({ APIClient.init(userID: $0) })
            .bind(to: APIRelay)
            .disposed(by: disposeBag)
        
        APIRelay
            .observeOn(ConcurrentDispatchQueueScheduler.init(qos: .background))
            .filter({ $0.userID > 0 })
            .flatMapLatest { $0.rx.requestUser($0.userID) }
            .map({ $0.value })
            .subscribeOn(MainScheduler.instance)
            .bind(to: user)
            .disposed(by: disposeBag)
    }
}
